#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "pt100_rw.h"
#include "pt100_test.h"
#include "thread_ctrl.h"
#include "ietPt100Lib.h"

#define PT100_RANGE_10V_LSB    305             /* 305uV */
#define PT100_RANGE_2V5_LSB    76              /* 76uV */
#define PT100_RANGE_5V_LSB     152             /* 152uV */

/* 接收线程 */
void *recv_pt100_thread(void *arg)
{
    struct pt100_dev_t *pdev = (struct pt100_dev_t *)arg;
    struct pt100_param_t *pparam = (struct pt100_param_t *)pdev->parent;
    struct thread_param_t *pthread = pdev->read_thread;
    int ret = 0;
    int i = 0;
    double value = 0;

    /* 检查参数是否有效 */
    if (!pthread || !pthread->name) {
        fprintf(stderr, "Invalid parameters for %s\n", __func__);
        return NULL;
    }

    /* 线程取消 SIGUSR1 的阻塞 */
    init_thread_user_signal();
    /* 配置 PT100 参数 */
    PT100MInit();
    // printf("Start %s receive thread...\n", pthread->name);
    while (!pthread->exit_sig) {
        for (i = 0; (pparam->read_cnt == -1 || i < pparam->read_cnt) && !pthread->exit_sig; i++) {
            /* 获取 PT100 数值 */
            ret = PT100MReadReal(pdev->index, &value);
            if (ret < 0) {
                printf("PT100MReadReal PT100 %2d value failed\n", pdev->index);
                return NULL;
            }
            printf("PT100MReadReal PT100 %2d value %.6lfC\n", pdev->index, value);
        }
        // printf("Read %s %d data done\n", pthread->name, pparam->read_cnt);
        break;
    }
    // printf("%s %s return\n", pthread->name, __func__);

    return NULL;
}
